﻿using System;
using System.Collections.Generic;

using System.Text;

namespace DotNETX.Authentication
{
    public class BasicTokenManager : ITokenManager
    {
        #region ITokenManager

        public string New()
        {
            return Guid.NewGuid().ToString();
        }

        public int Register(string token, object uniqueId)
        {
            if (token == null || uniqueId == null) return -1;
            if (Map.ContainsKey(token)) return -2;
            try
            {
                lock(Map)
                {
                    Map.Add(token, new UserSession() { Token = token, UniqueId = uniqueId, LoginTime = DateTime.Now, LastVistTime = DateTime.Now });
                    return 0;
                }
            }
            catch(Exception ex)
            {
                return -99;
            }
        }

        public int Unregister(string token)
        {
            if (token == null) return -1;
            if (!Map.ContainsKey(token)) return -2;
            try
            {
                lock (Map)
                {
                    Map.Remove(token);
                    return 0;
                }
            }
            catch (Exception ex)
            {
                return -99;
            }
        }

        public UserSession GetSession(string token)
        {
            if (token == null) return null;
            if (!Map.ContainsKey(token)) return null;
            else
            {
                lock(Map[token])
                {
                    Map[token].LastVistTime = DateTime.Now;
                }
                return Map[token];
            }
        }

        #endregion

        public BasicTokenManager()
        {
            Map = new Dictionary<string, UserSession>();
        }

        public Dictionary<string, UserSession> Map { get; private set; }
    }
}
